from rest_framework import serializers
from django_redis import get_redis_connection
from redis.exceptions import RedisError
import logging

logger = logging.getLogger('meiduo')


class RegisterSmscodeSerilizer(serializers.Serializer):

    text = serializers.CharField(label='图片验证码',max_length=4,min_length=4,required=True)
    image_code_id = serializers.UUIDField(label='图片验证码ID',required=True)

    def validate(self, attrs):

        redis = get_redis_connection('code')
        text_redis = redis.get('img_%s'%attrs['image_code_id'])

        if text_redis is None:
            raise serializers.ValidationError('验证码已过期')

        try:
            redis.delete('img_%s'%attrs['image_code_id'])
        except Exception as e:
            logger.error(e)

        if text_redis.decode().lower() != attrs['text'].lower():
            raise serializers.ValidationError('验证码输入错误')

        return attrs
